/**
* 作者: clz
* 日期: 2025-04-05 11:27:39
* 备注: 用户联盟信息
*/
package com.motu.monstercity.server.game.userdata;

import com.motu.monstercity.protocol.Common;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.commondata.bag.ItemId;
import com.motu.monstercity.server.game.commondata.maintask.MainTaskConstant;
import com.motu.monstercity.server.game.commondata.union.UnionBuildMain;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.logic.*;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class UserUnion extends UserUnionModel {
	public UserUnion() {
		super();
	}

	public void reset() {
		boolean update = false;
		long curTime = TimeUtils.getCurTime();
		if (!TimeUtils.isToday(resetTime)) {
			putResetTime(curTime);

			//清除今日贡献
			putDayContribution(0);

			//捐献
			putDonateNum("{}");
			putDonateProgressReward("");

			//重置折扣商店砍价和购买状态
			putDiscountShopPrice(0);
			putIsDiscountShopBuy((byte) 0);

			//重置运输中心每日记录
			putBusinessDayNum(0);

			//重置远征次数
			putBossBuyNum(0);
			putBossFreeNum(0);

			// 宝箱
//			putReceiveActiveBoxNum(0);
//			JsonArray newReceiveGiftBoxRecordArray = UnionManager.getReceiveGiftBoxReward(getUnionId(), getReceiveGiftBoxRecordArray());
//			if (!newReceiveGiftBoxRecordArray.isEmpty() && newReceiveGiftBoxRecordArray.size() != getReceiveGiftBoxRecordArray().size()) {
//				putActChargeReward(newReceiveGiftBoxRecordArray.toString()); // 过滤已领取且过期的礼盒ID
//			}

			update = true;
		}

		if (!TimeUtils.isSameWeek(curTime, actChargeTime)){
			//重置限时充值活动数据
			JsonArray actChargeTimeArray = UnionManager.getUnionActChargeTime();
			if (actChargeTimeArray.size() > 0) {
				long startTime = actChargeTimeArray.getLong(0);
				putActChargeReward("");
				putActChargePrice(0);
				putActChargeTime(startTime);
				update = true;
			}
		}
		if (update) {
			update();
		}
	}

	/**
	 * 是否在退出公会cd中
	 */
	public boolean isInLeaveCD() {
		return leaveTime + AllParam.UNION_LEAVE_CD_TIME > TimeUtils.getCurTime();
	}

	/**
	 * 是否是临时期
	 */
	public boolean isInTemp() {
		return tempEndTime > TimeUtils.getCurTime();
	}


	/**
	 * 是否有盟主权限
	 * @return
	 */
	public boolean IsPostMaster(){
		if (getPost() == UnionManager.POST_TYPE_MASTER) {
			return true;
		}
		return false;
	}

	/**
	 * 是否有副盟主以上权限
	 * @return
	 */
	public boolean IsPostDeputy(){
		if (getPost() == UnionManager.POST_TYPE_MASTER || getPost() == UnionManager.POST_TYPE_DEPUTY) {
			return true;
		}
		return false;
	}

	/**
	 * 是否有精英以上权限
	 * @return
	 */
	public boolean IsPostElite(){
		if (getPost() == UnionManager.POST_TYPE_MASTER || getPost() == UnionManager.POST_TYPE_DEPUTY || getPost() == UnionManager.POST_TYPE_ELITE) {
			return true;
		}
		return false;
	}

	/**
	 * 加入公会
	 */
	public void joinUnion(long actionUserId,UnionInfo unionInfo, UserInfo userInfo, Common.PBUserData.Builder pbUserData) {
		pbUserData = pbUserData != null? pbUserData:Common.PBUserData.newBuilder();

		long unionInfoId = unionInfo.getId();
		long userId = userInfo.getId();
		UnionMember unionMember = UnionManager.getUnionMember(unionInfoId,userId);
		if (unionMember == null) {
			unionMember = new UnionMember(unionInfoId,userId);
			unionMember.doCreate();
		}
		putUnionId(unionInfoId);

		// 更新用户展示数据
		GameUser.updateUserShow(userInfo, this);

		if (post != UnionManager.POST_TYPE_MASTER) {
			putTempEndTime(TimeUtils.getStartTimeOfDay(TimeUtils.getCurTime()) + TimeUtils.DAY);
		}
		// 加入公会消息推送
		if (post != UnionManager.POST_TYPE_MASTER) {
//			String msg = SystemWordManager.getSystemMsg(SystemWordManager.FAMILY_WELCOME_JOIN,
//					GameUser.getUserInfo(id).getUserName());
//			ChatManager.sendFamilyMessage(null, familyId, msg, 0, false,
//					ChatManager.CHAT_SUB_TYPE3, GameUser.getUserExtInfo(id).getLanguage(), true, "");
		}
		//更新联盟人数
		updateQueueNow();



		unionInfo.addMemberNum(1);
		unionInfo.update();
		//更新联盟战力列表
		UserPower userPower = GameUser.getUserPower(userId);
		UnionManager.updateUnionEarnRank(userInfo.getServerId(),unionInfoId,userPower.getMaxEarn());

		// 添加用户联盟宝箱
		UserUnionBox userUnionBox = UnionManager.getUserUnionBox(userId);
		if (userUnionBox == null) {
			UnionBoxInfo unionBoxInfo = UnionManager.getUnionBoxInfo(unionInfoId);
			if (unionBoxInfo == null) { // 兼容以前旧联盟数据（TODO 待删除）
				unionBoxInfo = new UnionBoxInfo(unionInfoId, unionInfo.getLevel());
				unionBoxInfo.insert();
			}
			userUnionBox = new UserUnionBox(userId, unionBoxInfo.getBoxId(), unionBoxInfo.getTotalNum());
			userUnionBox.insert();
		}

		// 添加联盟技能属性
		UnionManager.joinUnionAddPartnerSkillAdd(unionInfoId, userId, pbUserData);
		if (actionUserId != userId) { // 如果操作的人不是自己，需要推送指定的人刷新战力
			BoardcastManager.publicUnionSyncUserPower(userId);
		}

		//  更新任务进度
		MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_132, 1);// 更新主线任务,成就,日常任务的进度
		handleJoinUnion(userInfo,unionInfo);

	}
	// 处理联盟玩法相关资格
	public static void handleJoinUnion(UserInfo userInfo, UnionInfo unionInfo) {
		long userId = userInfo.getId();
		long unionId = unionInfo.getId();
		WorldBossManager.joinUnion(userId);  // 世界Boss
		UnionMobileManager.joinUnion(userInfo,unionId); // 联盟总动员
	}

	/**
	 * 退出公会
	 */
	public void exitUnion(long actionUserId,UnionInfo unionInfo,UserInfo userInfo,Common.PBUserData.Builder pbUserData,boolean isResign,boolean isUpdateRankPower) {
		pbUserData = pbUserData != null? pbUserData:Common.PBUserData.newBuilder();

		long unionInfoId = unionInfo.getId();
		long userId = userInfo.getId();
		// 删除公会成员对象
		UnionMember unionMember = UnionManager.getUnionMember(unionInfoId, userId);
		if (unionMember != null) {
			unionMember.delete();
		}
		// 更新用户公会数据
		putUnionId(0);
		putPost(0);
		putContribution(0);
		putLeaveTime(TimeUtils.getCurTime());
		putTempEndTime(0);

		// 更新用户展示数据
		GameUser.updateUserShow(userInfo, this);

		//更新联盟人数
		int memberNum = unionInfo.getMemberNum();
		unionInfo.putMemberNum(memberNum-1);
		unionInfo.update();

		//清除个人贡献
		putContribution(0);
		putDayContribution(0);

		if (isResign) {
			//主动退出 扣除50%货币--联盟币
			long useritemNum = BagManager.getUserItemNum(userInfo, ItemId.TYPE_UNION_COIN);
			long subNum = useritemNum  / 2 ;
			if (subNum > 0) {
				RewardManager.subReward(userInfo, ItemId.TYPE_UNION_COIN ,subNum,pbUserData, LogType.UNION_EXIT);
			}

		}

		//捐献模块不用处理,个人领奖和次数跟随时间重置

		//建筑建造模块
		ConcurrentHashMap<Integer, UnionBuildMain> unionBuildMainMap =  UnionManager.getUnionBuildMainMap();
		for (UnionBuildMain unionBuildMain : unionBuildMainMap.values()) {
			int buildId = unionBuildMain.getId();
			//建筑建造模块 记录要清楚
			UnionBuildUserAssistRecord unionBuildUserAssistRecord = UnionManager.getUnionBuildUserAssistRecord(unionId,buildId,userId);
			if (unionBuildUserAssistRecord != null){
				unionBuildUserAssistRecord.delete();
			}
			//建筑建设模块 记录要清除
			UnionBuildUserRecord unionBuildUserRecord = UnionManager.getUnionBuildUserRecord(unionId,buildId,userId);
			if (unionBuildUserRecord != null){
				unionBuildUserRecord.delete();
			}
		}
		//运输中心次数不做清除,记录做清除
		putBusinessDayNum(0);
		putBusinessTotalNum(0);
		//砍价商店的记录不做清除,砍价商店的次数和购买不做清除

		//充值的记录不做清除,砍价商店的次数和购买不做清除
		updateQueueNow();
		//更新联盟战力列表
		if (isUpdateRankPower){
			UserPower userPower = GameUser.getUserPower(userId);
			UnionManager.updateUnionEarnRank(userInfo.getServerId(),unionInfoId,-userPower.getMaxEarn());
		}
		// 处理玩家联盟宝箱信息
		UnionManager.dealUnionBoxInfoByLeave(userInfo, unionInfoId);

		// 重置联盟技能
		UnionManager.resetPartnerSkillAddByUserId(userInfo, pbUserData);
		if (actionUserId != userId) { // 如果操作的人不是自己，需要推送指定的人刷新战力
			BoardcastManager.publicUnionSyncUserPower(userId);
		}

		// 删除在联盟的求助信息
		UnionManager.deleteUnionHelpByUserId(userInfo.getId(), unionInfoId);

		// 处理联盟类玩法退盟相关操作
		handleQuitUnion(userInfo,unionInfo);
	}

	// 处理退出联盟的一些模块数据处理
	public static void handleQuitUnion(UserInfo userInfo,UnionInfo unionInfo) {
		long userId = userInfo.getId();
		long unionId = unionInfo.getId();
		WorldBossManager.quitUnion(userId);
		UnionMobileManager.quitUnion(userInfo,unionId);
	}


	public JsonObject getUserDonateJson(){
		JsonObject result = new JsonObject();
		if (!Tool.isEmpty(getDonateNum())){
			result = new JsonObject(getDonateNum());
		}
		return result;
	}

	public List<Integer> getUserDonateProgressReward(){
		List<Integer> result = new ArrayList<>();
		if (!Tool.isEmpty(getDonateProgressReward())) {
			String[] progressReward = getDonateProgressReward().replace(" ", "").split(";");// 去除空格 按;划分
			for (int i = 0; i < progressReward.length; i++) {
				result.add(Integer.parseInt(progressReward[i]));
			}
		}
		return result;
	}

	public List<Integer> getUserActChargeRewardList(){
		List<Integer> result = new ArrayList<>();
		if (!Tool.isEmpty(getActChargeReward())) {
			String[] progressReward = getActChargeReward().replace(" ", "").split(";");// 去除空格 按;划分
			for (int i = 0; i < progressReward.length; i++) {
				result.add(Integer.parseInt(progressReward[i]));
			}
		}
		return result;
	}

	//计算玩家运输中心可用次数
	public int countBusinessCurNum(boolean isUpdate) {
		int businessCurNum = 0;
		long businessTime = 0;
		long curTime = TimeUtils.getCurTime();
		long diffTime = curTime - getBusinessTime();
		int timeNum = 0;
		if (diffTime > AllParam.UNION_BUSINESS_ORDER_CD_TIME) {
			timeNum = (int) (diffTime / AllParam.UNION_BUSINESS_ORDER_CD_TIME);
		}
		if (timeNum > 0 ) {
			businessCurNum = getBusinessNum() + timeNum;
			if (businessCurNum > AllParam.UNION_BUSINESS_ORDER_MAX_NUM) {
				businessCurNum = AllParam.UNION_BUSINESS_ORDER_MAX_NUM;
				businessTime = curTime;
			} else {
				businessTime = getBusinessTime() + timeNum * AllParam.UNION_BUSINESS_ORDER_CD_TIME;
			}
			putBusinessNum(businessCurNum);
			putBusinessTime(businessTime);
			if (isUpdate) {
				update();
			}
		}
		return getBusinessNum();
	}

}
